package org.example.system.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.example.system.common.constant.SecurityConstants;
import org.example.system.common.result.Result;
import org.example.system.model.dto.UserAuthInfo;
import org.example.system.service.SysUserService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Tag(name = "在线用户管理")
@RestController
@RequestMapping("/api/v1/online")
@RequiredArgsConstructor
public class OnlineUserController {

    private final RedisTemplate<String, Object> redisTemplate;
    private final SysUserService sysUserService;

    @Operation(summary = "获取当前在线用户列表")
    @GetMapping("list")
    public Result<List<UserAuthInfo>> getOnlineUsers() {
        String pattern = SecurityConstants.ONLINE_USER_PREFIX + "*";
        Set<String> keys = redisTemplate.keys(pattern);

        List<UserAuthInfo> onlineUsers = new ArrayList<>();
        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                String userNameStr = key.replace(SecurityConstants.ONLINE_USER_PREFIX, "");

                UserAuthInfo userInfo = sysUserService.getUserAuthInfo(userNameStr);
                onlineUsers.add(userInfo);
            }
        }

        return Result.success(onlineUsers);
    }

    @Operation(summary = "强制用户下线")
    @DeleteMapping("/{userId}")
    @PreAuthorize("hasAuthority('sys:user:kick')")
    public Result<Void> kickUser(@PathVariable Long userId) {
        String onlineKey = SecurityConstants.ONLINE_USER_PREFIX + userId;
        String tokenBlacklistKey = SecurityConstants.BLACKLIST_TOKEN_PREFIX + userId;

        redisTemplate.delete(onlineKey);
        redisTemplate.delete(tokenBlacklistKey);

        return Result.success();

    }
}